package cn.edu.xaut.servlet;

import cn.edu.xaut.Dao.GoodsDao;
import cn.edu.xaut.bean.Goods;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet( name = "UserCart", urlPatterns = "/userCartServlet" )
public class UserCartServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置编码
        this.doPost( req, resp );
    }





    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置编码
        resp.setContentType( "text/html;charset=utf-8" );
        resp.setCharacterEncoding( "utf-8" );
        req.setCharacterEncoding( "utf-8" );

        if (req.getSession().getAttribute( "user" ) == null) {
            resp.getWriter().println( "请先登录,<a href='login.jsp'>返回登录</a>" );
            return;
        }

        HttpSession session = req.getSession(false);


        List<Goods> goodscarts=session.getAttribute("goodscarts")==null?new ArrayList<Goods>():(List<Goods>)session.getAttribute("goodscarts");
        float totalprice=session.getAttribute("totalprice")==null?0:(float)session.getAttribute("totalprice");

        //查询数据库
        GoodsDao goodsDao = new GoodsDao();
        String id = req.getParameter( "goodsid" );
        try {
            if(id!=null) {
                Goods goodstemp = goodsDao.findeById(id);
                System.out.println(goodstemp);
                if (goodstemp != null) {
                    goodscarts.add(goodstemp);
                }
                totalprice= goodstemp.getGoodsprice()+totalprice;
                session.setAttribute("goodscarts", goodscarts);
                session.setAttribute("totalprice", totalprice);
                req.getRequestDispatcher("/goods_cart.jsp").forward(req, resp);
            }
            else{
                req.getRequestDispatcher("/goods_cart.jsp").forward(req, resp);
            }
        } catch (SQLException e) {
            throw new RuntimeException( e );
        } catch (ClassNotFoundException e) {
            throw new RuntimeException( e );
        }

    }
}
